import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:get/get.dart';
import 'package:largefriends/entity/entities/lf_limit_entity.dart';
import 'package:largefriends/entity/entities/lf_token_entity.dart';
import 'package:largefriends/entity/entities/lf_user_entity.dart';
import 'package:largefriends/pages/lf_verify/lf_verify_logic.dart';
import 'package:largefriends/res/lf_string_ext.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../config/lf_route.dart';
import '../events/user_change_event.dart';
import 'manager/lf_event_helper.dart';
import 'manager/lf_payment_helper.dart';
import 'manager/lf_store_helper.dart';
import '../net/error_handle.dart';
import '../net/lf_api_url.dart';
import '../net/lf_dio_util.dart';
import '../net/lf_image_upload.dart';
import '../utils/lf_dialog_utils.dart';
import '../utils/lf_logger.dart';
import 'im/lf_im_service.dart';

class LfAuthService extends GetxService {
  LfUserEntity? currentAccount;
  LfTokenEntity? tokenEntity;
  int messageNotificationStatus = 1;
  LfLimitEntity? limitEntity;
  int currentSparkCnt = 0;
  int currentLikeCnt = 0;
  int currentWinkCnt = 0;
  int sparkLimitCnt = 10000;
  int winkLimitCnt = 10000;
  int likeLimitCnt = 10000;

  @override
  void onInit() async {
    var tokenMap = LfStorageManager.getMap("token_entity");
    tokenEntity = tokenMap.isEmpty ? null : LfTokenEntity.fromJson(tokenMap);
    var accountMap = LfStorageManager.getMap("user_info");
    currentAccount =
        accountMap.isEmpty ? null : LfUserEntity.fromJson(accountMap);
    if (tokenEntity == null || currentAccount == null) {
      ///二者缺一不可,缺了就算没登录
      tokenEntity = null;
      currentAccount = null;
      LfStorageManager.remove('token_entity');
      LfStorageManager.remove('user_info');
    }
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    if (loggedIn()) {
      refreshProfile();
      startIm();
    }
    LfPaymentHelper().initStoreInfo();
  }

  bool loggedIn() {
    return (tokenEntity != null && currentAccount != null);
  }

  refreshProfile() {
    LfDio.instance.get<LfUserEntity>(url: apiProfile, params: {
      'profId': currentAccount!.userId,
    }).then((value) {
      setUserEntity(value);
    });
  }

  void startIm() {
    LfIMService imService = Get.find();
    imService.connect();
  }

  void setToken(LfTokenEntity? tokenEntity) {
    this.tokenEntity = tokenEntity;
    if (this.tokenEntity != null) {
      LfStorageManager.setMap("token_entity", this.tokenEntity!.toJson());
    }
  }

  void setUserEntity(LfUserEntity? value) async {
    if (value == null) {
      loginOut();
    } else {
      currentAccount = value;
      await LfStorageManager.setMap("user_info", currentAccount!.toJson());
      startIm();
      refreshConfig();
      lfLogger.e("====UserChangeEvent=");
      LfEventHelper()
          .getEvent()
          .fire(UserChangeEvent(userChangeAction: UserChangeAction.userEntity));
      bottomNotification.value = showBottomNotification();
      if (currentAccount!.mandatoryVerificationFlag == 1 &&
          (currentAccount!.verified == 0 || currentAccount!.verified == 3)) {
        toVerifyPage(must: true);
      }
    }
  }

  void uploadProfilePhotos(List<AssetEntity> list) async {
    uploadPicture(fileList: list).then((value) {
      if (value.isNotEmpty) {
        currentAccount?.photos?.addAll(value);
        setUserEntity(currentAccount);
      }
    });
  }

  refreshConfig() async {
    if (limitEntity == null) {
      var timezone = DateTime.now().timeZoneName;
      try {
        timezone = await FlutterTimezone.getLocalTimezone();
      } catch (error) {
        timezone = DateTime.now().timeZoneName;
      }
      await LfDio().get<LfLimitEntity>(
        url: apiServiceConfig,
        params: {'timezone': timezone},
      ).then((value) {
        limitEntity = value;
        sparkLimitCnt = value.sparkLimit;
        likeLimitCnt = value.likeLimit;
        winkLimitCnt = value.winkLimit;
        currentSparkCnt = value.curSparkCnt;
        currentLikeCnt = value.curLikeCnt;
        currentWinkCnt = value.curWinkCnt;
      }, onError: (error) {});
    }
  }

  Future<bool> updateUserProfile({
    required Map<String, dynamic> data,
  }) async {
    // showLoading();
    return await LfDio()
        .post<LfUserEntity>(url: apiUpdateProfile, params: data)
        .then((result) {
      setUserEntity(result);
      hideLoading();
      return true;
    }, onError: (error) {
      hideLoading();
      if (error is NetError) {
        showSnackBar(error.msg);
      }
    });
  }

  void loginOut({bool jumpSplash = true}) async {
    LfIMService imService = Get.find();
    await imService.disconnect();
    await LfStorageManager.remove('token_entity');
    await LfStorageManager.remove('user_info');
    // LfSearchFilterHelper().clear();
    // LfCommunityFilterHelper().clear();
    tokenEntity = null;
    currentAccount == null;
    limitEntity = null;
    currentSparkCnt = 0;
    currentLikeCnt = 0;
    currentWinkCnt = 0;
    sparkLimitCnt = 10000;
    winkLimitCnt = 10000;
    likeLimitCnt = 10000;
    // LfUserCacheManager().clear();
    // LfPaymentHelper().clear();
    if (jumpSplash) {
      Get.offAllNamed(LFRoute.pathSplash);
    }
  }

  String lastLoginInfo() {
    return LfStorageManager.getString("last_login_info_tip",
            defaultValue: '') ??
        "";
  }

  updateLastLoginInfo(String tip) {
    LfStorageManager.putString("last_login_info_tip", tip);
  }

  Rx<BottomNotificationType> bottomNotification =
      Rx<BottomNotificationType>(BottomNotificationType.none);

  BottomNotificationType showBottomNotification() {
    if (currentAccount == null) {
      return BottomNotificationType.none;
    }
    if (currentAccount!.publicPhotos().isEmpty) {
      return BottomNotificationType.photo;
    } else if (currentAccount!.verified == 0) {
      return BottomNotificationType.verify;
    } else if (currentAccount!.verified == 3) {
      ///3代表认证失败了
      return BottomNotificationType.verifyFailed;
    }
    return BottomNotificationType.none;
  }

  int calculateInfo() {
    var value = 100;
    if (currentAccount!.photos!.length < 2) {
      value = value - 15;
    }
    if (currentAccount!.headline.isNullOrEmpty) {
      value = value - 8;
    }
    if (currentAccount!.about.isNullOrEmpty) {
      value = value - 8;
    }
    if (currentAccount!.matchAbout.isNullOrEmpty) {
      value = value - 8;
    }
    //
    List<int> infoScores = List.empty(growable: true);
    infoScores.add(currentAccount!.marital == 0 ? 1 : 0);
    infoScores.add(currentAccount!.height == 0 ? 1 : 0);
    infoScores.add(currentAccount!.body == 0 ? 1 : 0);
    infoScores.add(currentAccount!.ethnicity == 0 ? 1 : 0);
    infoScores.add(currentAccount!.religion == 0 ? 1 : 0);
    infoScores.add(currentAccount!.language == 0 ? 1 : 0);
    infoScores.add(currentAccount!.education == 0 ? 1 : 0);
    infoScores.add(currentAccount!.occupation == 0 ? 1 : 0);
    infoScores.add(currentAccount!.smoke == 0 ? 1 : 0);
    infoScores.add(currentAccount!.drink == 0 ? 1 : 0);
    infoScores.add(currentAccount!.haveChildren == 0 ? 1 : 0);
    infoScores.add(currentAccount!.pet == 0 ? 1 : 0);
    infoScores.add(currentAccount!.politicalBelief == 0 ? 1 : 0);
    var itemScore = (40 ~/ (infoScores.length)).floor();
    for (var element in infoScores) {
      if (element == 1) {
        value = value - itemScore;
      }
    }
    if (value < 10) {
      value = 10;
    }
    return value;
  }

  bool canSpark() {
    if (currentAccount!.isGold()) {
      return true;
    }
    return (likeLimitCnt > (currentLikeCnt + 1)) &&
        (sparkLimitCnt > (currentSparkCnt + 1));
  }

  bool canLike() {
    if (currentAccount!.isGold()) {
      return true;
    }
    return (likeLimitCnt > (currentLikeCnt + 1));
  }

  bool canWink() {
    if (currentAccount!.isGold()) {
      return true;
    }
    return (winkLimitCnt > (currentWinkCnt + 1));
  }
}

enum BottomNotificationType { verify, verifyFailed, photo, info, none }
